"""
Case Type   : 防篡改
Case Name   : 账本数据库基础语法适配(DDL/DML)--查看schema是否带有防篡改属性并验证权限
Create At   : 2024-07-22
Owner       : songjing20
Description :
    1.查询三权分立参数enableSeparationOfDuty，关闭数据库对象隔离属性
    2.创建不同权限用户
    3.sysadmin用户创建schema并指定防篡改选项
    4.不同权限用户查看schema是否都带有防篡改属性
    5.查看数据库对象隔离属性没有开启
    6.清理环境
Expect      :
    1.显示默认值off
    2.创建成功
    3.成功
    4.成功
    5.成功
    6.成功
History     :
"""

import os
import unittest

from yat.test import Node
from yat.test import macro
from testcase.utils.Constant import Constant
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Common import Common
from testcase.utils.Logger import Logger


class ModifyCase(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.node_pri = Node('PrimaryDbUser')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.common = Common()
        self.schema_name = 's_tamper_proof_0012'
        self.user_name = 'u_tamper_proof'
        self.user_privileges = {f'{self.user_name}_sys': 'sysadmin',
                                f'{self.user_name}_create': 'createrole',
                                f'{self.user_name}_audit': 'auditadmin',
                                f'{self.user_name}_noruser': '',
                                f'{self.user_name}_independent': 'independent',
                                f'{self.user_name}_mon': 'monadmin',
                                f'{self.user_name}_opr': 'opradmin',
                                f'{self.user_name}_pol': 'poladmin',
                                f'{self.user_name}_persistent': 'persistence'}

    def test_security(self):
        text = '-----step1:查询三权分立参数enableSeparationOfDuty，关闭数据库对象隔离属性;' \
               'expect:默认值off，成功-----'
        self.log.info(text)
        default_value = self.common.show_param('enableSeparationOfDuty')
        self.assertEqual("off", default_value, f'执行失败:{text}')
        sql_res = self.pri_sh.execut_db_sql(
            f"alter database {self.node_pri.db_name} "
            f"with disable private object;")
        self.log.info(sql_res)
        self.assertIn(self.constant.ALTER_DATABASE_SUCCESS_MSG, sql_res,
                      f'执行失败:{text}')

        text = '-----step2:创建不同权限用户;expect:成功-----'
        self.log.info(text)
        for user, privilege in self.user_privileges.items():
            create_res = self.pri_sh.execut_db_sql(
                f"drop user if exists {user} cascade;"
                f"create user {user} {privilege} "
                f"password '{macro.COMMON_PASSWD}';")
            self.log.info(create_res)
            self.assertIn(self.constant.CREATE_ROLE_SUCCESS_MSG, create_res,
                          f'执行失败:{text}')

        text = '-----step3:sysadmin用户创建schema并指定防篡改选项;expect:成功-----'
        self.log.info(text)
        sql = f'''drop schema if exists {self.schema_name} cascade;
        create schema {self.schema_name} with blockchain;'''
        sql_res = self.pri_sh.execut_db_sql(
            sql, sql_type=f'-U {self.user_name}_sys -W{macro.COMMON_PASSWD}')
        self.log.info(sql_res)
        self.assertIn(self.constant.CREATE_SCHEMA_SUCCESS_MSG, sql_res,
                      f'执行失败:{text}')

        text = '-----step4:不同权限用户查看schema是否都带有防篡改属性;' \
               'expect:查询成功-----'
        self.log.info(text)
        for user in self.user_privileges.keys():
            self.log.info(f'-- {user} 用户查询模式防篡改信息')
            res = self.pri_sh.execut_db_sql(
                f"select nspblockchain from pg_namespace "
                f"where nspname='{self.schema_name}';",
                sql_type=f'-U {user} -W{macro.COMMON_PASSWD}')
            self.log.info(res)
            self.assertIn('t\n(1 row)', res, f'执行失败:{text}')

        text = '-----step5:查看数据库对象隔离属性没有开启;expect:成功-----'
        self.log.info(text)
        sql_res = self.pri_sh.execut_db_sql(
            f"select * from pg_rlspolicies;",
            sql_type=f'-U {self.user_name}_sys -W{macro.COMMON_PASSWD}')
        self.log.info(sql_res)
        self.assertIn('(0 rows)', sql_res, f'执行失败:{text}')

    def tearDown(self):
        text = '-----step6:清理环境;expect:成功-----'
        self.log.info(text)
        drop_schema = self.pri_sh.execut_db_sql(
            f"drop schema if exists {self.schema_name} cascade;")
        self.log.info(drop_schema)
        drop_user_res = []
        for user in self.user_privileges.keys():
            drop_res = self.pri_sh.execut_db_sql(
                f"drop user if exists {user} cascade;")
            self.log.info(drop_res)
            drop_user_res.append(drop_res)
        self.assertIn(self.constant.DROP_SCHEMA_SUCCESS_MSG, drop_schema,
                      f'执行失败:{text}')
        self.assertEqual(
            9, drop_user_res.count(self.constant.DROP_ROLE_SUCCESS_MSG),
            f'执行失败:{text}')
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
